<?php
    
    require_once('../jacked_configMySQL.php');
    require('jacked_configpdnet.php');

	//if this isn't getting called via API, we need this
	function generateSourceID(){
		//welp this is kind of a huge faggotry
		include_once('jacked_configapilol.php');
		$uuid = $_SERVER['REMOTE_ADDR'];
		$sourcedb = jackedDBGetRow(JACKED_APILOL_DB_SOURCES, "`uuid` = '$uuid'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);
		if($sourcedb){
			//already have a source
			$source = array("id" => $sourcedb['id'], "uuid" => $sourcedb['uuid']);
		}else{
			//need to create a new source for this guy
			$source = array("id" => '', "uuid" => $uuid, "Application" => '52'); //this is the site goddammit
			$newID = jackedDBInsertValues(JACKED_APILOL_DB_SOURCES, $source);
			if(!$newID){
				return false;
			}
		}
		
		return $newID;
	}
	
    //should probably make a generic paginator function:
    //paginator(howmany, page)
    ////return the LIMIT string
    function paginator($howMany, $page){

        return " LIMIT " . ($howMany * ($page - 1)) . ", " . $howMany;
    }
	
	//takes an array of fields, checks against an array of allowed fields,
	////returns a string of csv fields suitable for mysql SELECT 
	function getFieldString($fields, $allowedFields = false){
		$fieldschecked = array();
		if($allowedFields){
			if($fields){
				foreach($fields as $field){
					if(in_array($field, $allowedFields))
						$fieldschecked[] = '`' . $field . '`';
				}
			}
		}
		if(empty($fieldschecked))
			$fieldstring = "*";
		else
			$fieldstring = implode(", ", $fieldschecked);
	
		return $fieldstring;
	}
    
    //for tag slugs
    function slugify($str){
        $str = strtolower(trim($str));
        $str = preg_replace('/[^a-z0-9-]/', '-', $str);
        $str = preg_replace('/-+/', "-", $str);
        
        return $str;
    }
    
    function getVotesLabel($num){
        $type = ($num >= 0)? 1 : 0;
        return jackedDBGetVal('name', JACKED_PDNET_DB_VOTESLABELS, '`positive` = \'' . $type . '\' OR `positive` = \'2\' ORDER BY RAND() LIMIT 1');
    }
	
	function getPostRank($postID){
		$myVotes = jackedDBGetval("votes", JACKED_PDNET_DB_POSTS, "`id` = '$postID'");
		return (jackedDBGetVal("function:COUNT(`id`)", JACKED_PDNET_DB_POSTS, "`votes` > '$myVotes'") + 1);
	}
    
    function getPost($postID, $tagFormat = 'array', $fields = array("id", "decision", "result", "votes", "date", "tags", "voted")){
		
		$fieldstring = getFieldString($fields, array("id", "decision", "result", "votes", "date",));
        $post = jackedDBGetRowVals($fieldstring, JACKED_PDNET_DB_POSTS, " `id` = '$postID' AND `alive` = '1'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);
        if(in_array('tags', $fields)){
            $post['tags'] = getPostTags($postID, $tagFormat);
            
        }
		
		if(in_array('voted', $fields))
			$post['voted'] = (didSourceVoteOnPost((function_exists('getMySourceID')? getMySourceID() : generateSourceID()), $postID))? 'true' : 'false';

        return $post;
    }

    //dis is a really good
	function getPosts($howMany, $orderby='', $page = 1, $tagFormat =  'array', $fields = array("id", "decision", "result", "votes", "date", "tags", "voted")){
		
		$query = "SELECT " . getFieldString($fields, array("id", "decision", "result", "votes", "date")) . " FROM " . JACKED_PDNET_DB_POSTS . " WHERE `alive` = '1'";
		$order = false;
		
		switch($orderby){
			case 'date_up':
				$order = 'ORDER BY `id` ASC';
				break;
			case 'date_down':
				$order = 'ORDER BY `id` DESC';
				break;
			case 'votes_up':
				$order = 'ORDER BY `votes` ASC';
				break;
			case 'votes_down':
				$order = 'ORDER BY `votes` DESC';
				break;
			case 'random':
				$query = "SELECT * FROM (SELECT `id` FROM " . JACKED_PDNET_DB_POSTS . " WHERE `alive` = '1' ORDER BY RAND() LIMIT $howMany) AS RANDOM_POSTS JOIN " . JACKED_PDNET_DB_POSTS . " ON " . JACKED_PDNET_DB_POSTS . ".`id` = RANDOM_POSTS.id";
				break;
			
			default:
				$order = 'ORDER BY `id` DESC';
				break;
		}
		
		$query .= ($order)? (" " . $order . paginator($howMany, $page)) : '';
				
		$result = jackedDBQuery($query);
		while($post = mysql_fetch_array($result, MYSQL_ASSOC)){
			if(in_array('tags', $fields))
				$post['tags'] = getPostTags($post['id'], $tagFormat);
			if(in_array('voted', $fields))
				$post['voted'] = didSourceVoteOnPost((function_exists('getMySourceID')? getMySourceID() : generateSourceID()), $post['id']);
				
			$final[] = $post;
		}
		
		return $final;
	}
	
	
	/////////////////////////////////////////////////////////////////////////////
	////////////warning: old PD1 dust////////////////////////////////////////////
	//////////////////////////////don't breathe this/////////////////////////////
	//to make it easier to still deal with some of the old code
	//gets the specifically requested part of a post based on boolean args,
	////tags isn't included because it never was and anything new should use
	////getPost with the fields limiter anyway, or getPostSource
	function getPostMeta($postID, $decision, $result, $ip, $votes){
		$fields = array();
		
		$decision? $fields[] = "decision" : null;
		$result? $fields[] = "result" : null;
		//getting ip in this way is no longer allowed so gtfo, use sources
		$votes? $fields[] = "votes" : null;

		return getPost($postID, $fields);
	}
	/////////////////////////////////////////////////////////////////////////////
	
	
	//get the Source info for a post
	function getPostSource($postID, $fields = array("uuid", "ip", "appID", "appName", "appPlatform")){
		
		if(in_array("appName", $fields) || in_array("appPlatform", $fields))
			$query = "SELECT S.uuid, S.ip, A.name, A.platform FROM " . JACKED_PDNET_DB_POSTS . " P, " . JACKED_APILOL_DB_SOURCES . " S, " . JACKED_APILOL_DB_APPS . " A WHERE A.id = S.Application AND S.id = P.Source AND P.id = '$postID'";
		else
			$query = "SELECT S.uuid, S.ip FROM " . JACKED_PDNET_DB_POSTS . " P, " . JACKED_APILOL_DB_SOURCES . " S WHERE S.id = P.Source AND P.id = '$postID'";
			
		$result = jackedDBQuery($query);
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		
		//i'd use getFieldString, but this is a special case and im lazy, so its a small faggotry
		$done = array();
        foreach($row as $key => $value){
            if(in_array($key, $fields))
                $done[$key] = $value;
        }
        return $done;
	}
	
    //returns tags for any postid
    ///type is either array(default) or csv (any value other than 'array') 
    function getPostTags($postID, $type = 'array'){
        $fields = ($type == 'array')? 'T.*' : 'T.name';
        
        $query = "SELECT $fields FROM Tag T, TagRel R WHERE R.pdID = '$postID' AND T.id = R.tID";
        $res = jackedDBQuery($query);
        $tempTags = array();
        $done = false;
                
        if($res){
            if($type == 'array'){
                while($aRow = mysql_fetch_array($res, MYSQL_ASSOC)){
                    $tempTags[] = $aRow;
                }
                $done = $tempTags;
            }else{
                while($aRow = mysql_fetch_array($res, MYSQL_ASSOC)){
                    $tempTags[] = $aRow[name];
                }
                $done = implode(', ', $tempTags);
            }
        
        }
       
        return $done;
    }    
    
    //returns an array of the info about a given tag id
    function getTagByID($id, $fields = array("id", "name", "usage", "slug")){
        $args = array();
        		
        $query = "SELECT " . getFieldString($fields, array("id", "name", "usage", "slug")) . " FROM " . JACKED_PDNET_DB_TAGS . " WHERE `id` = '$id'";
        
        $res = jackedDBQuery($query);
        $done = false;
        while($tagrow = mysql_fetch_array($res, MYSQL_ASSOC)){
            $done = $tagrow;
        }
        
        return $done;
    }
        
    //returns an array of tags
	//howmany of 0 returns all tags
    function getTags($howMany = '0', $sort = 'count_down', $fields = array("id", "name", "usage", "slug"), $page = false){
        $args = array();
        switch($sort){
            case 'name_up':
                $args["orderby"] = "name";
                $args["order"] = "ASC";
                break;
            case 'name_down':
                $args["orderby"] = "name";
                $args["order"] = "DESC";                
                break;
            case 'count_up':
                $args["orderby"] = "usage";
                $args["order"] = "ASC";
                break;
            case 'count_down':
                $args["orderby"] = "usage";
                $args["order"] = "DESC";
                break;
            default:
                $args["orderby"] = "usage";
                $args["order"] = "DESC";
                break;
        }
		
        $query = "SELECT " . getFieldString($fields, array("id", "name", "usage", "slug")) . " FROM " . JACKED_PDNET_DB_TAGS . " WHERE 1 ORDER BY `" . $args["orderby"] . "` " . $args["order"];

        if($page && $howMany != 0){
            $query .= paginator($howMany, $page);
        }elseif($howMany != 0){
			$query .= " LIMIT $howMany";
		}
        
        $res = jackedDBQuery($query);
        $done = array();
        while($aRow = mysql_fetch_array($res, MYSQL_ASSOC)){
            $done[] = $aRow;
        }
        
        return $done;
    }
    
    //returns an array of postids for a given tag id
    function getPostIDsByTagID($tID, $orderby = false, $howMany = false, $paged = false){
        $query = "SELECT P.id FROM " . JACKED_PDNET_DB_POSTS . " P, " . JACKED_PDNET_DB_TAGRELS . " R  WHERE `alive` = '1' AND R.tID = '" . $tID . "' AND P.id = R.pdID ";
		switch($orderby){
			case 'date_up':
				$order = 'ORDER BY `id` ASC';
				break;
			case 'date_down':
				$order = 'ORDER BY `id` DESC';
				break;
			case 'votes_up':
				$order = 'ORDER BY `votes` ASC';
				break;
			case 'votes_down':
				$order = 'ORDER BY `votes` DESC';
				break;
			
			default:
				$order = 'ORDER BY `id` DESC';
				break;
		}
		$query .= $order;
        if($paged && $howMany)
            $query .= paginator($howMany, $paged);
        $res = jackedDBQuery($query);
        $done = array();
                
        if($res){
            while($aRow = mysql_fetch_array($res, MYSQL_ASSOC)){
                $done[] = $aRow[id];
            }
        }
        
        return $done;
    }
    /* nah
    function getPostIDsByTagSlug($slug, $howMany = false, $paged = false){
        $id = jackedDBGetVal("id", JACKED_PDNET_DB_TAGS, "`slug` = '$slug'");
        
        return getPostIDsByTagID($id, '', $howMany, $paged);
    }*/
    
    function submitPost($decision, $result, $appname = 'THE FUCKING SITE'){
        $did = jackedDBInsertValues(JACKED_PDNET_DB_SUBMISSIONS, array(
            'id' => '',
            'postID' => '0',
            'posted' => '0', 
            'alive' => '1', 
            'decision' => $decision,
            'result' => $result, 
            'Source' => (function_exists('getMySourceID')? getMySourceID() : generateSourceID())));
            
        if($did){
            $subjectlol = "AN POOR DECISION GOT DID!";
        	$emailol = $decision . ", HASBECAME DONEDID OF " . $result . "\n\n FROM: " . $appname;
        	$headers = 'From: RevealYourSecrets@poordecisions.net' . "\r\n" .
            'Reply-To: noreply@poordecisions.net' . "\r\n";
            
        	mail('cwayne18@gmail.com', $subjectlol, $emailol, $headers);
        	mail('pope@poordecisions.net', $subjectlol, $emailol, $headers);
        }
        return $did;
    }
   
    /////////////////////////////
    //here there be voting shit//
    /////////////////////////////
	function didSourceVoteOnPost($sourceID, $postID){
		return (jackedDBgetRow(JACKED_PDNET_DB_VOTES, "`postID` = '$postID' AND `Source` = '$sourceID'", JACKED_DEFAULT_LINK, MYSQL_ASSOC))? true : false;
	}
	
	//returns the number of votes for a given post,
	////if $updateCache is false, returns cached value
	////if its true, recalculates based on VOTES table 
	////and updates cached value
	function getVotesForPost($postID, $updateCache = false){
	    if($updateCache){
	        $query = "SELECT `value` FROM " . JACKED_PDNET_DB_VOTES . " WHERE `postID` = '$postID'";
	        $result = jackedDBQuery($query);
	        $votes = 0;
	        while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
	            $votes += $row['value'];
	        }
	        
	        jackedDBUpdate(JACKED_PDNET_DB_POSTS, array("votes" => $votes), "`id` = '$postID'");
	    }else{
	        $votes = jackedDBGetVal('votes', JACKED_PDNET_DB_POSTS, "`id` = '$postID'");
	    }
	    
	    return $votes;
	}
	
	function voteOnPost($postID, $type, $sourceID){
	    $value = false;
	    if(!didSourceVoteOnPost($sourceID, $postID)){
			//this is where to change to make certain sources have different score values
	        $value = ($type == 'sink')? -1 : 1;
	        $did = jackedDBInsertValues(JACKED_PDNET_DB_VOTES, array("id" => '', "postID" => $postID, "value" => $value, "Source" => $sourceID));
	        if($did){
	            $value = getVotesForPost($postID, true);
	        }
	    }
	    return $value;
	} 
?>